package com.augurit.gzcgwsp.ywcmn.dwr;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.augurit.common.base.form.ResultForm;
import com.augurit.common.system.util.WebContextUtils;
import com.augurit.common.system.web.auth.form.LoginUserForm;
import com.augurit.gzcgwsp.common.dwr.BaseDwrService;
import com.augurit.gzcgwsp.excelimportexport.service.IYwRqQyjyxkCyryzkdjbService;
import com.augurit.gzcgwsp.excelimportexport.service.IYwRqQyjyxkGdyjgqjgdjbService;
import com.augurit.gzcgwsp.excelimportexport.service.IYwRqQyjyxkImportservice;
import com.augurit.gzcgwsp.excelimportexport.service.IYwRqQyjyxkJbxxbService;
import com.augurit.gzcgwsp.excelimportexport.service.IYwRqQyjyxkPzrqgyzdjbService;
import com.augurit.gzcgwsp.excelimportexport.service.IYwRqQyjyxkQysbclmcService;
import com.augurit.gzcgwsp.excelimportexport.service.IYwRqQyjyxkRqjszdjbService;
import com.augurit.gzcgwsp.excelimportexport.service.IYwRqQyjyxkRqqxdylbService;
import com.augurit.gzcgwsp.excelimportexport.service.IYwRqQyjyxkRqqxsbylbService;
import com.augurit.gzcgwsp.excelimportexport.service.IYwRqQyjyxkRqqxssdjbService;
import com.augurit.gzcgwsp.excelimportexport.service.IYwRqQyjyxkRqssdjbService;
import com.augurit.gzcgwsp.excelimportexport.service.IYwRqQyjyxkRqssylbService;
import com.augurit.gzcgwsp.excelimportexport.service.IYwRqQyjyxkRypbqkService;
import com.augurit.gzcgwsp.excelimportexport.service.IYwRqQyjyxkZyaqjsglryzkService;
import com.augurit.gzcgwsp.excelimportexport.service.IYwRqQyjyzzImportservice;
import com.augurit.gzcgwsp.jzfqwczz.common.entity.YwYnJzfqwczzXckctp;
import com.augurit.gzcgwsp.jzfqwczz.common.service.IYwYnJzfqwczzXckctpService;
import com.augurit.gzcgwsp.jzfqwczz.common.web.form.YwYnJzfqwczzXckctpForm;
import com.augurit.gzcgwsp.jzfqwczz.service.IYwYnJzfqwczcJbxxService;
import com.augurit.gzcgwsp.ljzyz.service.IYwYnBusinfoService;
import com.augurit.gzcgwsp.qyzz.entity.YwRqRyzzEquipment;
import com.augurit.gzcgwsp.qyzz.service.IYwRqQyzzEquipmentService;
import com.augurit.gzcgwsp.rqqyjyxk.service.IYwRqQyjyxkService;
import com.augurit.gzcgwsp.rqqyjyxk.web.form.YwRqQyjyxkForm;
import com.augurit.gzcgwsp.ssylb.web.form.YwRqRqssylbForm;
import com.augurit.gzcgwsp.webservice.SFTPUtil;
import com.augurit.gzcgwsp.ywcmn.service.IYwComSjclService;
import com.augurit.gzcgwsp.ywcmn.service.IYwDzgzListService;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComSjclForm;
import com.augurit.gzcgwsp.ywcmn.web.form.YwDzgzListForm;
import com.google.gson.Gson;

/**
 * 无刷新文件上传
 * 
 * @author huyoxo
 */
@Controller
@RemoteProxy
public class FileUploadCntl extends BaseDwrService {
    private static final Log log=LogFactory.getLog(FileUploadCntl.class);
	@Autowired
	private IYwComSjclService service;
	@Autowired
	private IYwDzgzListService ywDzgzListService;
	@Autowired
	private IYwRqQyjyxkService ywRqQyjyxkService;
	private final String attachePath = "/resources/AttacheFile";

	@Autowired
	private IYwRqQyjyxkJbxxbService ywRqQyjyxkJbxxbService;
	@Autowired
	private IYwRqQyjyzzImportservice ywRqQyjyzzImportservice;
	
	@Autowired
	private IYwRqQyjyxkGdyjgqjgdjbService ywRqQyjyxkGdyjgqjgdjbService;
	
	@Autowired
	private IYwRqQyjyxkCyryzkdjbService ywRqQyjyxkCyryzkdjbService;
	
	@Autowired
	private IYwRqQyjyxkZyaqjsglryzkService ywRqQyjyxkZyaqjsglryzkService;
	
	@Autowired
	private IYwRqQyjyxkRqqxssdjbService ywRqQyjyxkRqqxssdjbService;
	
	@Autowired
	private IYwRqQyjyxkRqqxdylbService ywRqQyjyxkRqqxdylbService;
	
	@Autowired
	private IYwRqQyjyxkRqqxsbylbService ywRqQyjyxkRqqxsbylbService;
	
	@Autowired
	private IYwRqQyjyxkRqssdjbService ywRqQyjyxkRqssdjbService;
	
	@Autowired
	private IYwRqQyjyxkRqssylbService ywRqQyjyxkRqssylbService;
	
	@Autowired
	private IYwRqQyjyxkQysbclmcService ywRqQyjyxkQysbclmcService;
	
	@Autowired
	private IYwRqQyjyxkPzrqgyzdjbService ywRqQyjyxkPzrqgyzdjbService;
	
	@Autowired
	private IYwRqQyjyxkRypbqkService ywRqQyjyxkRypbqkService;
	
	@Autowired
	private IYwRqQyjyxkRqjszdjbService ywRqQyjyxkRqjszcpzqcjqzdjbService;
	
	@Autowired
	private IYwRqQyjyxkImportservice ywRqQyjyxkImportservice;
	
	@Autowired
	private IYwYnBusinfoService ywYnBusinfoService;
	@Autowired
	private IYwRqQyzzEquipmentService ywRqQyzzEquipmentService; 
	@Autowired
	private IYwYnJzfqwczcJbxxService ywYnJzfqwczcJbxxService;
	
	@Autowired
	private IYwYnJzfqwczzXckctpService ywYnJzfqwczcXckctpService;
	
	
	/**
	 * 上传附件文件 --------------------------------------
	 * 
	 * @param params
	 * @param uploadFile
	 * @return
	 */
	@RemoteMethod
	public String uploadAttache(String params, InputStream uploadFile)
			throws Exception {
		YwComSjclForm paramForm = (YwComSjclForm) this.toBeanFromJson(params,
				YwComSjclForm.class);
		// if (StringUtils.isBlank(paramForm.getAcceptNo())) return null;

		WebContext ctx = WebContextFactory.get();
		LoginUserForm loginUser = (LoginUserForm) ctx.getSession()
				.getAttribute(WebContextUtils.SES_LOGIN_USER);
		if(uploadFile!=null && uploadFile.available()>0){//有附件时候
				byte[] b = new byte[uploadFile.available()];
				// 随机生成文件名后缀
				String formatDate = new SimpleDateFormat("yyyyMMddHHmmss")
						.format(new Date());
				int random = new Random().nextInt(1000000);
		
				String targetFilePath = ctx.getHttpServletRequest().getSession()
						.getServletContext().getRealPath(this.attachePath);
				String filePathSep = "\\";
				if (targetFilePath.indexOf("/") >= 0)
					filePathSep = "/";
				String targetFileName = formatDate + random + "."
						+ paramForm.getFiletype();
				String targetFileRealPath = targetFilePath + filePathSep
						+ targetFileName;
				// File target = new File(targetPath, targetFile);
				// FileUtils.copyFile(file, target);
				FileOutputStream targetFile = new FileOutputStream(new File(
						targetFileRealPath));
				uploadFile.read(b);
				targetFile.write(b);
				targetFile.flush();
				targetFile.close();
				uploadFile.close();
				// 保存文件信息到数据库
				paramForm.setFilepath(this.attachePath + "/" + targetFileName);
				paramForm.setScr(loginUser.getUser().getUserName());
				paramForm.setSctime(new Date());
				service.saveByUpload(paramForm);
			
		}else{
			service.updateAttach(paramForm);
		
		}
		return super.getJsonString(paramForm);
	}

	/**
	 * 上传附件文件 --------------------------------------
	 * 
	 * @param params
	 * @param uploadFile
	 * @return
	 */
	@RemoteMethod
	public String changeChxstate(String params) throws Exception {
		YwComSjclForm paramForm = (YwComSjclForm) this.toBeanFromJson(params,
				YwComSjclForm.class);

		Long ajid = paramForm.getAjid();
        Long tplid = paramForm.getTplid();
//        Long clid = paramForm.getId();
        String tplcode = paramForm.getTplcode();
        List<YwComSjclForm> ywComSjclFormlist = service.getFjList(ajid, tplid, tplcode);        
        if(ywComSjclFormlist.size()>0){//如果有一个以上的附件数，则全部删掉
        	for(int i = 0;i<ywComSjclFormlist.size();i++){
        		YwComSjclForm paramForm2 = ywComSjclFormlist.get(i);
        		service.changeChxstate(paramForm2,paramForm.getOtherFlag());
        	} 
        }else{
        	service.changeChxstate(paramForm,paramForm.getOtherFlag());
        }

		return "success";
	}

	/**
	 * 上传设施一览表的附件
	 * 
	 * @param form
	 */
	@RemoteMethod
	public String saveSsylb(String params, InputStream uploadFile)
			throws Exception {
	    JSONObject json=JSONObject.fromObject(params);
		YwRqQyjyxkForm paramForm = (YwRqQyjyxkForm) JSONObject.toBean(json, YwRqQyjyxkForm.class);
		YwRqRqssylbForm form = (YwRqRqssylbForm) JSONObject.toBean(json, YwRqRqssylbForm.class);

		  WebContext ctx = WebContextFactory.get();
          String contextPath = ctx.getHttpServletRequest().getSession()
                    .getServletContext().getRealPath("");
		 ywRqQyjyxkService.saveSsylb(contextPath,form);
		return super.getJsonString(paramForm);
		// return null;
	}
	
	/**
	 * 保存企业主要设备
	 * @param form
	 */
	@RemoteMethod
	public String saveEquipment(String params, InputStream uploadFile)
			throws Exception {
		Gson gson = new Gson();
		YwRqRyzzEquipment entity = gson.fromJson(params, YwRqRyzzEquipment.class);
		ywRqQyzzEquipmentService.saveEntity(entity);
		return super.getJsonString(entity);
		
	}	
	
	/**
	 * 上传电子盖章ceb文件
	 * 
	 * @param params
	 * @param uploadFile
	 * @return
	 * @throws Exception
	 */
	@RemoteMethod
	public String uploadDzgz(String params, InputStream uploadFile)
			throws Exception {
		Gson gson = new Gson();
		YwDzgzListForm paramForm = gson.fromJson(params, YwDzgzListForm.class);
		byte[] b = new byte[uploadFile.available()];
		//String targetFilePath = "F:/Tomcat 6.0/webapps/gzcgwsp/resources/AttacheFile";
		 WebContext ctx = WebContextFactory.get();
         String contextPath = ctx.getHttpServletRequest().getSession()
         .getServletContext().getRealPath("");
         String targetFilePath =contextPath+"/resources/AttacheFile";
         targetFilePath=targetFilePath.replace("/",File.separator);
		// 随机生成文件名后缀
		String formatDate = new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date());
		int random = new Random().nextInt(1000000);
		String targetFileName = formatDate + random + ".ceb";
		String targetFiletype = paramForm.getFiletype();
		// String targetFileRealPath = targetFilePath + filePathSep
		// +paramForm.getAjid()+"_"+targetFileName+"."+targetFiletype;
		String targetFileRealPath = targetFilePath +File.separator + formatDate + random + ".ceb";
		FileOutputStream targetFile = new FileOutputStream(new File(targetFileRealPath));
		uploadFile.read(b);
		targetFile.write(b);
		targetFile.flush();
		targetFile.close();
		uploadFile.close();
		paramForm.setUploaddate(new Date());
		paramForm.setFilepath("/resources/AttacheFile/" +formatDate + random + ".ceb");
		//同时上传一份到另外一台服务器
		SFTPUtil.uploadOtherFile("/resources/AttacheFile/" +formatDate + random + ".ceb", targetFileRealPath);
		
		ywDzgzListService.save(paramForm);

		
		// return super.getJsonString(paramForm);
		return null;
	}

	/**
	 * 导入燃气处信息EXCEL
	 * 
	 * @param params
	 * @param uploadFile
	 * @return
	 * @throws Exception
	 */
	@RemoteMethod
	public String uploadSqb(String type,long rqjyxkid,long qyid, String acceptNo, String username,String params,InputStream uploadFile){
		String error="";
		  Map<String,String> paramMap=getMapByJson(params);
		  WebContext ctx = WebContextFactory.get();
	      String contextPath = ctx.getHttpServletRequest().getSession()
	                .getServletContext().getRealPath("");
	      paramMap.put("contextPath", contextPath);
	      Map<String,String> msgMap=new HashMap<String,String>();
	    try{
			if(type!=null && !"".equals(type)){//企业资质导入
			    try {
			        msgMap=ywRqQyjyzzImportservice.importExcel(rqjyxkid,qyid, acceptNo, username, paramMap, uploadFile);
                } catch (Exception e) {
                    log.error(acceptNo+"导入数据出现错误"+e);
                    error="系统出现错误,导入数据失败";
                    msgMap.put("error", error);
                }
			    
			}else{//许可证导入
				ywRqQyjyxkImportservice.importExcel(rqjyxkid,qyid, acceptNo, username, params, uploadFile, contextPath);
				msgMap.put("error", error);
			}
			//ActionContext ctx = ActionContext.getContext();     
			//HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE);  
			//response.getWriter().print(error);
              
		}catch(Exception e){
 			e.printStackTrace();
 		}
		return super.getJsonString(msgMap);
	}
	
	/**
	 * 导入余泥处车辆信息EXCEL
	 * 
	 * @param params
	 * @param uploadFile
	 * @return
	 * @throws Exception
	 */	
	@RemoteMethod
	public String uploadBusinfo(long qyid,long ajid,String gsmc,InputStream uploadFile){
		try{
			ywYnBusinfoService.uploadBusinfo(qyid,ajid,gsmc, uploadFile);
			return super.getJsonString(new ResultForm(true));
		}catch(Exception e){
			return super.getJsonString(new ResultForm(false));
 		}		
	}
	
	/**
	 * 导入余泥处-处置证-新增发证-检查表的附件
	 * @param ajid 案件ID
	 * @param fjFlag 附件标志
	 * @param uploadFile 流
	 * @throws Exception
	 */
	@RemoteMethod
	public String uploadJcbFj(long ajid,String fjFlag,String fjOldName,String fjType,InputStream uploadFile){
		String fileName = "";
		WebContext ctx = WebContextFactory.get();
        String contextPath = ctx.getHttpServletRequest().getSession()
        .getServletContext().getRealPath("");
        String targetFilePath =contextPath+"/resources/AttacheFile/";
        targetFilePath=targetFilePath.replace("/",File.separator);
		try{
			fileName = ywYnJzfqwczcJbxxService.uploadJcbFj(targetFilePath,ajid,fjFlag,fjOldName,fjType, uploadFile);
			return super.getJsonString(new ResultForm(true,fileName));
		}catch(Exception e){
			e.printStackTrace();
			return super.getJsonString(new ResultForm(false));
			
 		}		
	}
	
	/**
	 * 保存设施一览表 附件
	 * @param fjOldName 附件原名
	 * @param fjType 附件类型
	 * @param uploadFile 流
	 * @throws Exception
	 */
	@RemoteMethod
	public String uploadSsylbFj(String fjOldName,String fjType, InputStream uploadFile)throws Exception{
		String fileName = "";
		WebContext ctx = WebContextFactory.get();
        String contextPath = ctx.getHttpServletRequest().getSession()
        .getServletContext().getRealPath("");
        String targetFilePath =contextPath+"/resources/AttacheFile/";
        targetFilePath=targetFilePath.replace("/",File.separator);
		try{
			fileName = ywRqQyjyxkService.uploadSsylbFj(targetFilePath,fjOldName,fjType, uploadFile);
			return super.getJsonString(new ResultForm(true,fileName));
		}catch(Exception e){
			e.printStackTrace();
			return super.getJsonString(new ResultForm(false));
			
 		}		
	}

	/**
	 * 下载需要电子盖章的文档
	 * 
	 * @param destUrl
	 * 电子盖章文档的网络地址
	 * @return
	 * @throws Exception
	 */
	@RemoteMethod
	public String downloadDzgz(String destUrl) throws Exception {

		FileOutputStream fos = null;
		BufferedInputStream bis = null;
		HttpURLConnection httpUrl = null;
		String fileName = "D:\\"
				+ destUrl.substring(destUrl.lastIndexOf("/") + 1);

		URL url = null;
		byte[] buf = new byte[512];
		int size = 0;
		// 建立链接
		url = new URL(destUrl);
		httpUrl = (HttpURLConnection) url.openConnection();
		// 连接指定的资源
		httpUrl.connect();
		// 获取网络输入流
		bis = new BufferedInputStream(httpUrl.getInputStream());
		// 建立文件
		fos = new FileOutputStream(fileName);
		System.out.println("正在获取链接[" + destUrl + "]的内容...\n将其保存为文件[" + fileName
				+ "]");
		// 保存文件
		while ((size = bis.read(buf)) != -1)

			fos.write(buf, 0, size);
		fos.close();
		bis.close();
		httpUrl.disconnect();
		return null;
	}
	
	
	/**
	 * 将字符串转换为json字符串转换为map
	 * @param jsonString
	 * @return
	 */
	private   static Map<String,String> getMapByJson(String jsonString) {
	    JSONObject jsonObject = JSONObject.fromObject(jsonString);
	    Iterator<String> keyIter = jsonObject.keys();
	    String key;
	    String value;
	    Map<String, String> valueMap = new HashMap<String, String>();
	    while (keyIter.hasNext()) {
	     key = keyIter.next();
	     value = (String) jsonObject.get(key);
	     valueMap.put(key, value);
	    }
	    return valueMap;
	}
	
	/**
	 * 余泥处-现场勘察图片  上传
	 * @param ajid 案件ID
	 * @param templateCode 业务模板编号
	 * @param uploadFile 流
	 * @throws Exception
	 */
	@RemoteMethod
	public String uploadXckcImage(long ajid,String templateCode,String fjOldName,String fjType,InputStream uploadFile){
//		String fileName = "";
		YwYnJzfqwczzXckctpForm ywYnJzfqwczzXckctpForm = null;
		WebContext ctx = WebContextFactory.get();
        String contextPath = ctx.getHttpServletRequest().getSession()
        .getServletContext().getRealPath("");
        String targetFilePath =contextPath+"/resources/AttacheFile/";
        targetFilePath=targetFilePath.replace("/",File.separator);
		try{
//			fileName = ywYnJzfqwczcXckctpService.uploadXckcImage(targetFilePath,ajid,templateCode,fjOldName,fjType, uploadFile);
			ywYnJzfqwczzXckctpForm = ywYnJzfqwczcXckctpService.uploadXckcImage(targetFilePath,ajid,templateCode,fjOldName,fjType, uploadFile);
			return super.getJsonString(new ResultForm(true,ywYnJzfqwczzXckctpForm));
		}catch(Exception e){
			e.printStackTrace();
			return super.getJsonString(new ResultForm(false));
			
 		}		
	}
}
